<template>
    <el-dialog
            title="上传证书"
            :visible.sync="show"
    >
        <div v-loading="loadState" class="box">
            <el-form
                    ref="form"
                    label-width="110px"
                    :model="licence"
                    :rules="rule"
                    @submit.native.prevent
                    @keyup.enter.native="sure"
            >
                <el-form-item label="证照名称" prop="licenceName">
                    <el-input v-model="licence.licenceName" placeholder="请输入证照名称"></el-input>
                </el-form-item>
                <el-row :gutter="5">
                    <el-col :span="12">
                        <el-form-item label="证号" prop="licenceNumber">
                            <el-input v-model="licence.licenceNumber" placeholder="请输入证号"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="证书等级" prop="licenceLevel">
                            <el-input v-model="licence.licenceLevel" placeholder="请输入证书等级"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="5">
                    <el-col :span="12">
                        <el-form-item label="发证机关" prop="authorization">
                            <el-input v-model="licence.authorization" placeholder="请输入发证机关"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="续证准备时间" prop="renewalPreparingTime">
                            <el-select style="width: 100%" v-model="licence.renewalPreparingTime"
                                       placeholder="请选择续证准备时间">
                                <el-option
                                        v-for="item in preparingTimeOption"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="有效时间" prop="validTime">
                    <el-date-picker
                            style="width: 100%"
                            v-model="licence.validTime"
                            type="datetimerange"
                            range-separator="至"
                            start-placeholder="证件有效开始日期"
                            end-placeholder="证件失效日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="上传文件" v-loading="uploading">
                    <el-upload
                            action="#"
                            :show-file-list="false"
                            :http-request="uploadMethod"
                            :before-remove="beforeRemove"
                            :on-success="uploadSuccess"
                            :file-list="fileList"
                            :class="{'none':Boolean(currentFile)}"
                            accept=".jpg, .jpeg, .png, .gif"
                    >
                        <i slot="trigger" class="el-icon-plus uploader file-input-btn"></i>
                    </el-upload>
                    <uploader-previewer @click="rmImg" class="previewer" v-if="currentFile" :src="fileToUrl(currentFile)"></uploader-previewer>
                </el-form-item>
                <el-row>
                    <el-col :span="12" :offset="12">
                        <el-form-item>
                            <el-button type="primary" @click="sure">确 定</el-button>
                            <el-button @click="cancel">取 消</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
    </el-dialog>
</template>

<script>
    import UploaderPreviewer from "~/components/file-list/licence-file-list/UploaderPreviewer";
    import moment from "moment";
    const preparingTimeOption = [
        {value: 1000 * 60 * 60 * 24 * 30, label: "到期前一个月"},
        {value: 1000 * 60 * 60 * 24 * 30 * 3, label: "到期前三个月"},
        {value: 1000 * 60 * 60 * 24 * 365, label: "到期前一年内"},
    ];
    export default {
        name: "EnterpriseLicenceUpload",
        components: {UploaderPreviewer},
        props: {
            uploadUrl: {
                type: String,
                default: "/licence/enterprise/upload"
            },
            deleteUrl: {
                type: String,
                default: "/file/rm"
            },
            downloadUrl: {
                type: String,
                default: "/file/download"
            },
            changeFileUrl: {
                type: String,
                default: "/file/mv"
            },
            updateLicenceUrl:{
                type: String,
                default: "/licence/enterprise",
            },
        },
        data() {
            return {
                licence: {
                    licenceNumber: '',
                    validTime: [],
                    licenceName: "",
                    licenceLevel: "",
                    authorization: "",
                    renewalPreparingTime: null,
                },
                fileList:[],
                preparingTimeOption,
                uploading: false,
                show: false,
                currentDir: null,
                currentFile: null,
                rule: {
                    licenceName: [{required: true, message: "请输入证照名称。", trigger: "blur"}],
                },
                loadState: false,
            };
        },
        methods: {
            open(dir) {
                if (!dir) {
                    this.$message({
                        showClose: true,
                        message: "请稍等，文件夹未加载完成。如果长时间未响应，您可以尝试刷新浏览器。",
                        type: "error"
                    });
                    return undefined;
                }
                if(this.currentDir&&this.currentDir.id!==dir.id){
                    this.rmImg();
                    this.clearForm();
                }
                this.currentDir = dir;
                this.show = true;
            },
            cancel() {
                this.show = false;
            },
            sure() {
                if(this.uploading){
                    this.$alert('证照文件正在上传中，请稍后再提交表单。', '提示', {type:"warn"});
                    return undefined;
                }
                if(!this.currentFile){
                    this.$alert('请上传证照文件。', '提示', {type:"error"});
                    return undefined;
                }
                this.$refs.form.validate(valid=>{
                    if(valid){
                        this.loadState = true;
                        this.submit().then(()=>{
                            this.$emit("upload-success", this.currentDir);
                            this.show = false;
                            this.resetForm();
                        }).catch(e=>{
                            this.$alert(e.message, '上传失败', {type:"error"});
                        }).finally(()=>{
                            this.loadState = false;
                        });
                    }else {
                        this.$alert('请先填写表单。', '提示', {type:"error"});
                    }
                });
            },
            async submit(){
                const licence = {
                    licenceNumber: this.licence.licenceNumber,
                    licenceName: this.licence.licenceName,
                    licenceLevel: this.licence.licenceLevel,
                    authorization: this.licence.authorization,
                    renewalPreparingTime: this.licence.renewalPreparingTime,
                    directoryMetaId: this.currentFile.directoryMetaId,
                    fileMetaId: this.currentFile.fileMetaId,
                };
                if(this.licence.validTime && this.licence.validTime.length>=2) {
                    licence.validStartingTime = moment(this.licence.validTime[0]).format("YYYY-MM-DD HH:mm:ss");
                    licence.validCutOffTime = moment(this.licence.validTime[1]).format("YYYY-MM-DD HH:mm:ss");
                }
                try {
                    const response = await this.$http.put(this.updateLicenceUrl,licence);
                    if(response.data.resultCode!=="200"){
                        throw response.data;
                    }
                    this.currentFile = response.data.parameter;
                }catch (e) {
                    console.error(e);
                    throw new Error(e.message);
                }
            },
            async uploadMethod(file) {
                console.log("发起上传:",file);
                let formData = new FormData();
                const parentDir = this.currentDir;
                formData.append("file", file.file);
                formData.append("parentId", parentDir.id);
                let source = this.$http.CancelToken.source();
                file.file.cancelSource = source;
                this.uploading = true;
                return new Promise((resolve, reject) => {
                    this.$http({
                        url: this.uploadUrl,
                        method: 'post',
                        data: formData,
                        //上传进度
                        onUploadProgress: (progressEvent) => {
                            let num = progressEvent.loaded / progressEvent.total * 100 | 0;  //百分比
                            file.onProgress({percent: num})     //进度条
                        },
                        cancelToken: source.token,
                        timeout: -1,
                    }).then(response => {
                        resolve(response.data.parameter); //上传成功(打钩的小图标)
                    }).catch(err => {
                        reject(err);
                    });
                }).finally(()=>{
                    this.uploading = false;
                });
            },
            beforeRemove(file) {
                if (file.status !== "uploading") return true;
                return new Promise((resolve, reject) => {
                    this.$confirm(`文件${file.name}正在上传中，是否要取消上传？`, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        resolve();
                    }).catch(() => {
                        reject();
                    });
                });
            },
            async uploadSuccess(fileMeta,file) {
                if(!fileMeta) return undefined;
                if (this.currentFile) {
                    try {
                        await this.deleteFile(this.currentFile);
                        this.currentFile = null;
                    } catch (_e) {}
                }
                this.currentFile = fileMeta;
                file.meta = fileMeta;
                file.url = this.fileToUrl(fileMeta);
                console.log("上传成功",file);
                this.fileList.push(file);
            },
            async deleteFile(file) {
                try {
                    await this.$http.delete(`${this.deleteUrl}/${file.id}`);
                } catch (e) {
                    console.log(e);
                }
            },
            rmImg(){
                if(this.currentFile) this.deleteFile(this.currentFile);
                this.currentFile = null;
            },
            clearForm(){
                this.licence.validTime = [];
                this.licence.licenceName = "";
                this.licence.authorization = "";
                this.licence.licenceLevel = "";
                this.licence.renewalPreparingTime = null;
            },
            resetForm(){
                this.clearForm();
                this.currentFile = null;
            },
            fileToUrl(file){
                const extName = file.ext?'.'+file.ext:'';
                return `${this.$http.defaults.baseURL}${this.downloadUrl}/${file.id}${extName}`;
            },
            checkout(dir,file){
                this.currentDir = dir;
                this.currentFile = file;
                this.licence.licenceNumber = file.licenceNumber;
                this.licence.licenceName = file.licenceName;
                this.licence.licenceLevel = file.licenceLevel;
                this.licence.authorization = file.authorization;
                this.licence.renewalPreparingTime = file.renewalPreparingTime;
                this.licence.validTime = [];
                if(file.validStartingTime) this.$set(this.licence.validTime,0,file.validStartingTime);
                if(file.validCutOffTime) this.$set(this.licence.validTime,1,file.validCutOffTime);
                this.show = true;
            }
        },
        mounted() {
            this.$on("open", this.open);
            this.$on("checkout", this.checkout);
        }
    }
</script>

<style scoped>
    .uploader {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        overflow: hidden;
        height: 35px;
        width: 35px;
        font-size: 1.5em;
        line-height: 35px;
    }

    .uploader:hover {
        color: #409EFF;
        border-color: #409EFF;
    }

    .box {
        width: 90%;
        margin: 0 auto;
    }

    .none {
        display: none;
    }
    .previewer{
        height: 85px;
    }
</style>

<style>
    .file-input-btn + .el-upload__input {
        display: none;
    }
</style>
